import functions from "@/utils/functions.js";
// import {
// 	getToken,
// 	logout
// } from "@/utils/auth.js";
// import store from "../store/index.js"
import {
	publicKey,
	appId,
	appSecret
} from "../config/config.js";
import CryptoJS from "crypto-js";

const aesKeyList = {};

const service = (params) => {
	return new Promise((relove, reject) => {
		// console.log(`REQUEST：${params.url}`, params.data);
		if (params.data) {
			if (!params.data.hideLoading) {
				functions.showWaiting();
			}
			delete params.data.hideLoading;
		}
		
		let requestId = functions.getRandomString(40);
		
		//加密秘钥
		aesKeyList[requestId] = functions.getRandomString(16);
		
		//加密秘钥
		// aesKeyList[params.url]=functions.getRandomString(16);

		//加密参数秘钥
		// const secretKey = functions.encryptRsa(publicKey, aesKeyList[requestId]);
		//加密请求报文
		const encryptValue = functions.encryptAes(JSON.stringify(params.data), aesKeyList[requestId]);
		//生成签名
		const sign = CryptoJS.MD5(JSON.stringify(params.data) + appSecret).toString();

		// let postParams = {
			// appId: appId,
			// encryptValue: encryptValue,
			// sign: sign,
			// secretKey: secretKey,
			// requestId: requestId
		// };
		const postParams = params.data

		uni.request({
			url: functions.getDomain() + params.url,
			data: postParams,
			method: params.method,
			timeout:30000,
			dataType: "json",
			header: {
				"content-type": "application/json",
				"Authorization": '9d08998e-ba51-47da-aca4-eb277bcd9dee'
			}
		}).then(res => {
			let that = this;
			functions.closeWaiting();

			//停止下拉刷新
			uni.stopPullDownRefresh();
			// console.log('ressssssssssssss',res)
			// let [err, success] = res;
			let success = res

			// if (!err) {

				if (success.statusCode == 200) {
					// console.log('======success',success);
					let data = success.data;
					
					//秘钥保存的key
					let responseArrKey = data.requestId || '';
					
					//参数解密
					// data = JSON.parse(functions.decryptAes(data.encryptValue, aesKeyList[responseArrKey]));
					// console.log(`RESPONSE：${params.url}`, data);
					let code = data.code;

					// console.log('success',success);
					switch (~~code) {
						case 200:
							relove(data.data);
							break;
						case 22:
							store.commit('setToken', "");
							store.commit('setUserInfo', {});
							functions.error(data.msg);
							reject(data.data);
							break;
						case 401:
							store.commit('setToken', "");
							store.commit('setUserInfo', {});
							functions.error(data.msg);
							break;
						default:
							if(data.msg){
								functions.error(data.msg);
							}
							reject(data);
					}

				//触发维护界面，关闭所有页面，跳到维护中
				}else if(success.statusCode == 503){
					uni.reLaunch({
						url: '/pages/maintain/index'
					});
				}else {
					// 请求失败
					functions.error("服务器请求失败");
					reject();
				}

			// } else {
			// 	//请求失败
			// 	functions.error("服务器请求失败");
			// 	reject();
			// }

		});

	})



}
export default service;
